package com.tangsm.api.demo.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tangsm.api.demo.annotation.ResponseResultBody;
import com.tangsm.api.demo.domain.Student;
import com.tangsm.api.demo.service.StudentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

/**
 * mybatis 实例
 *
 * @author 湯神码
 * @date 2020/10/26
 */
@RestController
@RequestMapping("/mybatis")
@ResponseResultBody
public class MybatisDemoController {

    Logger logger = LoggerFactory.getLogger(MybatisDemoController.class);

    @Autowired
    private StudentService studentService;

    @Autowired
    private MessageSource messageSource;

    /**
     * 根据学号查询学生信息
     *
     * @param sno
     * @return
     */
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public Student queryStudentBySno(String sno) {
        logger.debug("测试query，sno={}", sno);
        return this.studentService.queryStudentBySno(sno);
    }

    @PostMapping("/add")
    public String addStudent(@RequestBody @Valid Student student) {
        int i = studentService.add(student);
        String message = i > 0 ? "成功" : "失败";
        logger.info("新增学生信息{}", i > 0 ? "成功" : "失败");
        ObjectMapper mapper = new ObjectMapper();
        String studentToString = null;
        try {
            studentToString = mapper.writeValueAsString(student);
            logger.info("Json 实体转换 String 实例, studentToString = {}", studentToString);
        } catch (JsonProcessingException e) {
            logger.error("Json 转换 String 异常...", e);
        }
        return "成功";
    }
}